import React, { useEffect, useState } from "react";
import { useRef } from "react";
import { Button, Form, Input, Modal, Space, Table, message } from "antd";
import { DeleteOutlined, UploadOutlined } from "@ant-design/icons";
import {
  getDetectionPointDataSetFileList,
  deleteDetectionPointDataSetFile,
  createDetectionPointDataSetFile,
  createDetectionPointDataSetFileAll,
  DetectionPointDataSetFileItem,
} from "../../api/gis";
import AddDataPickerModal from "./AddDataPickerModal";

interface DetectionFilesProps {
  dataSetId: number;
  refreshTree: () => void;
  planetId: number;
  inspectionAreaId: number;
  detectionPointId: number;
}

const DetectionFiles: React.FC<DetectionFilesProps> = ({ dataSetId, refreshTree, planetId, inspectionAreaId, detectionPointId }) => {
  const [files, setFiles] = useState<DetectionPointDataSetFileItem[]>([]);
  const [fileLoading, setFileLoading] = useState(false);
  const [selectedFileKeys, setSelectedFileKeys] = useState<React.Key[]>([]);
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);
  const [addModalOpen, setAddModalOpen] = useState(false);

  // 表格容器与固定高度
  const tableContainerRef = useRef<HTMLDivElement | null>(null);
  const [tableScrollY, setTableScrollY] = useState<number>(0);

  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      // 参照地名管理一致的高度计算
      const pageHeight = window.innerHeight;
      const breadcrumbHeight = 48;
      const tabsHeaderHeight = 46;
      const filterFormHeight = 0;
      const actionButtonsHeight = 56;
      const padding = 242;
      const availableHeight = pageHeight - breadcrumbHeight - tabsHeaderHeight - filterFormHeight - actionButtonsHeight - padding;
      const tableHeaderHeight = 39;
      const scrollHeight = Math.max(availableHeight - tableHeaderHeight, 100);
      setTableScrollY(scrollHeight);
      const tableBody = tableContainerRef.current.querySelector('.ant-table-body') as HTMLElement | null;
      if (tableBody) {
        tableBody.style.height = scrollHeight + 'px';
        tableBody.style.maxHeight = scrollHeight + 'px';
      }
    }
  };

  const [filterForm] = Form.useForm();

  const fetchFiles = async () => {
    if (!dataSetId) return;
    setFileLoading(true);
    try {
      const response = await getDetectionPointDataSetFileList({ data_set_id: dataSetId, page: current, page_size: pageSize });
      if (response.code === 200) {
        setFiles(response.data.list);
        setTotal(response.data.count);
      } else {
        message.error(response.msg || "获取文件列表失败");
      }
    } catch (error) {
      console.error("获取文件列表失败:", error);
      message.error((error as any)?.message || "获取文件列表失败");
    } finally {
      setFileLoading(false);
    }
  };

  useEffect(() => {
    fetchFiles();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dataSetId, current, pageSize]);

  useEffect(() => {
    const timer = setTimeout(() => {
      calculateTableScrollHeight();
    }, 100);
    const onResize = () => calculateTableScrollHeight();
    window.addEventListener('resize', onResize);
    return () => {
      clearTimeout(timer);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  const handleBatchDelete = () => {
    if (selectedFileKeys.length === 0) {
      message.warning("请选择要删除的文件");
      return;
    }
    Modal.confirm({
      title: "确认批量删除",
      content: `确定要删除选中的 ${selectedFileKeys.length} 个文件吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const response = await deleteDetectionPointDataSetFile({ ids: selectedFileKeys as number[] });
          if (response.code === 200) {
            message.success("批量删除成功");
            setSelectedFileKeys([]);
            fetchFiles();
            refreshTree();
          } else {
            message.error(response.msg || "批量删除失败");
          }
        } catch (error) {
          console.error("批量删除失败:", error);
          message.error((error as any)?.message || "批量删除失败");
        }
      },
    });
  };

  const handleSingleDelete = (record: DetectionPointDataSetFileItem) => {
    Modal.confirm({
      title: "确认删除",
      content: `确定要删除文件 "${record.file_name}" 吗？`,
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const response = await deleteDetectionPointDataSetFile({ ids: [record.id] });
          if (response.code === 200) {
            message.success("删除成功");
            fetchFiles();
            refreshTree();
          } else {
            message.error(response.msg || "删除失败");
          }
        } catch (error) {
          console.error("删除文件失败:", error);
          message.error((error as any)?.message || "删除失败");
        }
      },
    });
  };

  const handlePickerOk = async (selectedData: any[]) => {
    try {
      const files = selectedData.map((item) => ({
        data_type: item.data_type,
        product_id: item.product_id,
      }));
      const response = await createDetectionPointDataSetFile({
        planet_id: planetId,
        inspection_area_id: inspectionAreaId,
        detection_point_id: detectionPointId,
        data_set_id: dataSetId,
        files,
      });
      if (response.code === 200) {
        message.success("导入成功");
        setAddModalOpen(false);
        fetchFiles();
        refreshTree();
      } else {
        message.error(response.msg || "导入失败");
      }
    } catch (error) {
      console.error("导入失败:", error);
      message.error((error as any)?.message || "导入失败");
    }
  };

  // 全部添加回调
  const handleAddAll = async (filterParams: any) => {
    try {
      // 构造全部添加参数，直接使用自己的planetId
      const params = {
        planet_id: planetId,  // 直接使用自己的planetId
        inspection_area_id: inspectionAreaId,
        detection_point_id: detectionPointId,
        data_set_id: dataSetId,
        ...filterParams
      };

      // 调用全部添加接口
      const response = await createDetectionPointDataSetFileAll(params);
      
      if (response.code === 200) {
        message.success("全部添加成功");
        setAddModalOpen(false);
        fetchFiles();
        refreshTree();
      } else {
        message.error(response.msg || "全部添加失败");
      }
    } catch (error) {
      console.error("全部添加失败:", error);
      message.error((error as any)?.message || "全部添加失败");
    }
  };

  return (
    <div
      style={{
        height: "100%",
        display: "flex",
        flexDirection: "column",
      }}
    >
      {/* <div style={{ flexShrink: 0 }}>
        <Form layout="inline" className="filter-form" form={filterForm} labelCol={{ style: { width: 120 } }}>
          <Form.Item label="文件名称" name="file_name" style={{ width: 320 }}>
            <Input placeholder="请输入文件名称搜索（本地过滤占位）" allowClear />
          </Form.Item>
          <Form.Item style={{ paddingLeft: 40 }}>
            <Space>
              <Button type="primary" onClick={() => message.info("筛选条件后端支持后接入")}>筛选</Button>
              <Button onClick={() => filterForm.resetFields()}>清除</Button>
            </Space>
          </Form.Item>
        </Form>
      </div> */}

      <div
        style={{
          marginBottom: 16,
          marginTop: 16,
          display: "flex",
          justifyContent: "space-between",
          alignItems: "center",
          flexShrink: 0,
        }}
      >
        <div>
          <Button type="primary" danger onClick={handleBatchDelete} disabled={selectedFileKeys.length === 0}>
            批量删除
          </Button>
        </div>

        <Space>
          <Button icon={<UploadOutlined />} type="primary" onClick={() => setAddModalOpen(true)}>
            批量导入
          </Button>
        </Space>
      </div>

      <div style={{ flex: 1, overflow: "hidden" }}>
        <div className="pds-table-container" style={{ height: "100%" }} ref={tableContainerRef}>
          <Table
            rowSelection={{
              selectedRowKeys: selectedFileKeys,
              columnWidth: 50,
              onChange: (newKeys) => setSelectedFileKeys(newKeys),
            }}
            columns={[
              { title: "ID", dataIndex: "id", key: "id", width: 80, ellipsis: true },
              { title: "文件名称", dataIndex: "file_name", key: "file_name", width: 200, ellipsis: true },
              { title: "文件路径", dataIndex: "file_path", key: "file_path", width: 260, ellipsis: true },
              { title: "任务", dataIndex: "task", key: "task", width: 120, ellipsis: true },
              { title: "载荷", dataIndex: "dm_zhname", key: "dm_zhname", width: 120, ellipsis: true },
              { title: "数据等级", dataIndex: "data_level", key: "data_level", width: 120, ellipsis: true },
              { 
                title: "文件大小", 
                dataIndex: "data_size", 
                key: "data_size", 
                width: 120, 
                ellipsis: true,
                render: (value: number) => {
                  if (value === null || value === undefined) return '-';
                  const mb = (value / (1024 * 1024)).toFixed(2);
                  return `${mb} MB`;
                }
              },
              { title: "创建时间", dataIndex: "create_time", key: "create_time", width: 180, ellipsis: true },
              {
                title: "操作",
                key: "action",
                width: 160,
                fixed: "right" as const,
                align: "center" as const,
                render: (_: any, record: DetectionPointDataSetFileItem) => (
                  <Space size="small">
                    <Button type="link" size="small" danger icon={<DeleteOutlined />} onClick={() => handleSingleDelete(record)}>
                      删除
                    </Button>
                  </Space>
                ),
              },
            ]}
            dataSource={files}
            rowKey="id"
            loading={fileLoading}
            pagination={{
              current,
              pageSize,
              total,
              showSizeChanger: true,
              pageSizeOptions: ["10", "20", "50"],
              onChange: (page, size) => {
                setCurrent(page);
                setPageSize(size!);
              },
              showTotal: (t) => `共 ${t} 条`,
            }}
            scroll={{ y: tableScrollY, x: "max-content" }}
            bordered
            size="small"
          />
        </div>
      </div>

      <AddDataPickerModal
        open={addModalOpen}
        onCancel={() => setAddModalOpen(false)}
        onOk={handlePickerOk}
        onAddAll={handleAddAll}
      />
    </div>
  );
};

export default DetectionFiles;


